package com.platform.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.SysOptionLog;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.utils.HttpContextUtils;
import com.platform.utils.IPUtils;
import com.platform.utils.ShiroUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 系统日志，切面处理类
 */
@Aspect
@Component
public class SysOptionLogAspect {
    @Autowired
    private SysOptionLogService sysOptionLogService;

    @Autowired
    private ExtractCoinService extractCoinService;

    @Autowired
    private IncomeCoinService incomeCoinService;

    @Autowired
    private IncomeService incomeService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserAssetService userAssetService;

    /**
     * 切点
     */
    @Pointcut("@annotation(com.platform.annotation.SysOptionLog)")
    public void logPointCut() {

    }

    /**
     * 前置通知
     *
     * @param joinPoint 连接点
     */
    @Before("logPointCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysOptionLogEntity entity = new SysOptionLogEntity();
        SysOptionLog syslog = method.getAnnotation(SysOptionLog.class);
        if (syslog != null) {
            //注解上的描述
            entity.setOperation(syslog.value());
        }
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        entity.setMethod(className + "." + methodName + "()");

        //请求的参数
        Object[] args = joinPoint.getArgs();
        JSONObject json = (JSONObject) JSON.toJSON(args[0]);
        Integer id = json.getInteger("id");
        entity.setParams(JSON.toJSONString(json));
        int type = this.getType(methodName);
        //获取参数ID
        Long uid = this.getUserId(type, json);
        //根据Type和ID获取原来的Json字符串
        String formerEntity = getFormerEntity(type, id);
        //存储原来的对象字符串
        entity.setFormer(formerEntity);
        entity.setType(type);
        entity.setUserId(uid);
        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        entity.setIp(IPUtils.getIpAddr(request));

        //用户名
        SysUserEntity sysUserEntity = ShiroUtils.getUserEntity();
        String username = "";

        if (null != sysUserEntity) {
            username = ShiroUtils.getUserEntity().getUsername();
        }
        entity.setUsername(username);

        entity.setCreateDate(new Date());
        //保存系统日志
        sysOptionLogService.save(entity);
    }

    private int getType(String methodName) {
        if (methodName.contains("order")) {
            return 1;
        } else if (methodName.contains("orderSpc")) {
            return 2;
        } else if (methodName.contains("orderAmount")) {
            return 3;
        } else if (methodName.contains("extract")) {
            return 4;
        } else if (methodName.contains("asset")) {
            return 5;
        } else if (methodName.contains("income")) {
            return 6;
        } else if (methodName.contains("coin")) {
            return 7;
        } else {
            return -1;
        }
    }

    private Long getUserId(int type, JSONObject json) {
        if (type == 1) {
            //type ==1 order 商城订单
            return json.getLong("userId");
        } else if (type == 2) {
            //type ==2 orderSpc Spc订单
            return json.getLong("userId");
        } else if (type == 3) {
            //type ==3 orderAmount 奖金订单
            return json.getLong("userId");
        } else if (type == 4) {
            //type ==4 extract 闪兑记录
            return json.getLong("userId");
        } else if (type == 5) {
            //type ==5 asset 用户资产
            return json.getLong("uid");
        } else if (type == 6) {
            //type ==6 income 用户收益明细
            return json.getLong("userid");
        } else if (type == 7) {
            //type ==7 coin 运动链收益记录
            return json.getLong("uid");
        } else {
            return 0l;
        }
    }

    /**
     * @Description: 用于获取源数据
     */
    private String getFormerEntity(int type, Integer id) {
        if (type == 1) {
            //type ==1 order 商城订单
            OrderEntity orderEntity = orderService.queryObject(id);
            JSONObject json = (JSONObject) JSON.toJSON(orderEntity);
            return JSON.toJSONString(json);
        } else if (type == 2) {
            //type ==2 orderSpc Spc订单
            OrderEntity orderEntity = orderService.queryObject(id);
            JSONObject json = (JSONObject) JSON.toJSON(orderEntity);
            return JSON.toJSONString(json);
        } else if (type == 3) {
            //type ==3 orderAmount 奖金订单
            OrderEntity orderEntity = orderService.queryObject(id);
            JSONObject json = (JSONObject) JSON.toJSON(orderEntity);
            return JSON.toJSONString(json);
        } else if (type == 4) {
            //type ==4 extract 闪兑记录
            ExtractCoinEntity extractCoinEntity = extractCoinService.queryObject(id.longValue());
            JSONObject json = (JSONObject) JSON.toJSON(extractCoinEntity);
            return JSON.toJSONString(json);
        } else if (type == 5) {
            //type ==5 asset 用户资产
            UserAssetEntity userAssetEntity = userAssetService.queryObject(id);
            JSONObject json = (JSONObject) JSON.toJSON(userAssetEntity);
            return JSON.toJSONString(json);
        } else if (type == 6) {
            //type ==6 income 用户收益明细
            IncomeEntity incomeEntity = incomeService.queryObject(id);
            JSONObject json = (JSONObject) JSON.toJSON(incomeEntity);
            return JSON.toJSONString(json);
        } else if (type == 7) {
            //type ==7 coin 运动链收益记录
            IncomeCoinEntity incomeCoinEntity = incomeCoinService.queryObject(id.longValue());
            JSONObject json = (JSONObject) JSON.toJSON(incomeCoinEntity);
            return JSON.toJSONString(json);
        }
        return "未知操作";
    }
}
